import Point from './point'

export default class Queue<T> {
  #head?: Point<T>

  #tail?: Point<T>

  #size = 0

  constructor() {
    this.clear()
  }

  enqueue(value: T): void {
    const point = new Point(value)

    if (this.#head) {
      this.#tail!.next = point
      this.#tail = point
    } else {
      this.#head = point
      this.#tail = point
    }
    this.#size++
  }

  dequeue(): T | undefined {
    const current = this.#head
    if (!current) return

    this.#head = this.#head!.next
    this.#size = this.#size - 1
    return current.value
  }

  get size(): number {
    return this.#size
  }

  clear(): void {
    this.#head = undefined
    this.#tail = undefined
    this.#size = 0
  }
  /**
   * Generator 函数执行后，返回一个遍历器对象。该对象本身也具有Symbol.iterator属性，执行后返回自身
   */

  * [Symbol.iterator](): IterableIterator<T> {
    let current = this.#head

    while (current) {
      yield current.value
      current = current.next
    }
  }
}
